package com.sts.frame;

import cn.hutool.core.lang.Singleton;
import com.formdev.flatlaf.FlatClientProperties;
import com.sts.Main;
import com.sts.common.utils.CompletableFutureUtil;
import com.sts.common.utils.ImageUtil;
import com.sts.common.utils.JdbcConnectionUtil;
import com.sts.panel.StsTaskPanel;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystems;
import java.time.Year;
import java.util.function.BiConsumer;

import static com.formdev.flatlaf.FlatClientProperties.*;

/**
 * @author lsl
 * @since 2025年07月15日 18:16
 */
@Slf4j
public class RootFrame extends JFrame {

    private static final String TITLE = "STS-2.0.0";
    private static final int HEIGHT = 900;
    private static final int WEIGHT = 1200;

    private static final String LOG_DIR = System.getProperty("user.home") +
            FileSystems.getDefault().getSeparator() +
            ".sts" +
            FileSystems.getDefault().getSeparator() +
            "logs";

    private static final String CONFIG_DIR = System.getProperty("user.home") +
            FileSystems.getDefault().getSeparator() +
            ".sts";

    private JTabbedPane tabbedPane;

    public RootFrame() {
        setSize(WEIGHT, HEIGHT);
        setTitle(TITLE);
        setLayout(new BorderLayout());

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                JdbcConnectionUtil.closeAll();
                super.windowClosing(e);
            }
        });

        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        initUI();
        setVisible(true);
    }

    private void initUI() {
        initMenu();
        initTabbedPane();
    }

    private void initTabbedPane() {
        tabbedPane = new JTabbedPane();
        tabbedPane.putClientProperty(TABBED_PANE_TAB_CLOSABLE, true);
        tabbedPane.putClientProperty(TABBED_PANE_TAB_CLOSE_TOOLTIPTEXT, "Close");
        tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        tabbedPane.putClientProperty(TABBED_PANE_TAB_CLOSE_CALLBACK,
                (BiConsumer<JTabbedPane, Integer>) (_, tabIndex) -> {
                    tabbedPane.remove(tabIndex);
                    int tabCount = tabbedPane.getTabCount();
                    if (tabCount <= 0) {
                        StsTaskPanel stsTaskPanel = new StsTaskPanel();
                        tabbedPane.addTab("数据采集", Singleton.get(ImageUtil.class).getImportIcon(), stsTaskPanel, stsTaskPanel.getPanelName());
                    }
                });
        add(tabbedPane, BorderLayout.CENTER);

        StsTaskPanel stsTaskPanel = new StsTaskPanel();
        tabbedPane.addTab("数据采集", Singleton.get(ImageUtil.class).getImportIcon(), stsTaskPanel, stsTaskPanel.getPanelName());
    }

    private void initMenu() {
        JMenuBar jMenuBar = new JMenuBar();
        add(jMenuBar, BorderLayout.NORTH);

        // 一级菜单
        JMenu functionMenu = new JMenu("功能");
        jMenuBar.add(functionMenu);
        JMenu operationMenu = new JMenu("操作");
        jMenuBar.add(operationMenu);
        JMenu helpMenu = new JMenu("帮助");
        jMenuBar.add(helpMenu);

        // 操作 > 数据采集
        JMenuItem sts = new JMenuItem("数据采集");
        functionMenu.add(sts);
        sts.addActionListener(_ -> CompletableFutureUtil.runAndThrowException(() -> {
            StsTaskPanel stsTaskPanel = new StsTaskPanel();
            tabbedPane.addTab("数据采集", Singleton.get(ImageUtil.class).getImportIcon(), stsTaskPanel, stsTaskPanel.getPanelName());
            tabbedPane.setSelectedComponent(stsTaskPanel);
        }));

        // 操作 > 打开配置文件夹
        JMenuItem openConfig = new JMenuItem("打开配置文件夹");
        operationMenu.add(openConfig);
        openConfig.addActionListener(_ -> CompletableFutureUtil.runAndThrowException(() -> {
            try {
                Desktop.getDesktop().open(new File(CONFIG_DIR));
            } catch (IOException ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            }
        }));

        // 操作 > 打开日志文件夹
        JMenuItem openLog = new JMenuItem("打开日志文件夹");
        operationMenu.add(openLog);
        openLog.addActionListener(_ -> CompletableFutureUtil.runAndThrowException(() -> {
            try {
                Desktop.getDesktop().open(new File(LOG_DIR));
            } catch (IOException ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            }
        }));

        // 帮助 > 开源
        JMenuItem openSource = new JMenuItem("开源");
        helpMenu.add(openSource);

        String link = "https://gitee.com/lsl6958/sts";
        String labelStr = """
                <html><a href="#">https://gitee.com/lsl6958/sts</a></html>
                """;
        JLabel linkLabel = new JLabel(labelStr);
        linkLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        linkLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(new URI(link));
                } catch (IOException | URISyntaxException ex) {
                    log.error(ex.getMessage(), ex);
                    JOptionPane.showMessageDialog(linkLabel,
                            "Failed to open '" + link + "' in browser.",
                            "开源", JOptionPane.PLAIN_MESSAGE);
                }
            }
        });

        JLabel tutorialLabel = new JLabel("开源地址");
        tutorialLabel.putClientProperty(FlatClientProperties.STYLE_CLASS, "h2");
        openSource.addActionListener(_ -> JOptionPane.showMessageDialog(
                Main.rootFrame,
                new Object[]{
                        tutorialLabel,
                        linkLabel,
                },
                "开源", JOptionPane.PLAIN_MESSAGE)
        );

        // 帮助 > 关于
        JMenuItem about = new JMenuItem("关于");
        helpMenu.add(about);
        JLabel titleLabel = new JLabel(TITLE);
        titleLabel.putClientProperty(FlatClientProperties.STYLE_CLASS, "h1");
        about.addActionListener(_ -> JOptionPane.showMessageDialog(
                Main.rootFrame,
                new Object[]{
                        titleLabel,
                        "Source Transform Sink",
                        " ",
                        "Copyright 2024-" + Year.now() + " RabbitHareLu",
                },
                "关于", JOptionPane.PLAIN_MESSAGE)
        );
    }

}
